package com.tpsix.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tpsix.security.ProjectConfigurationProperties;
import com.tpsix.security.JwtTokenManager;
import com.tpsix.util.R;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Authentication success processor
 */
@Component
@AllArgsConstructor
public class TpsixAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    private final JwtTokenManager tokenManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = this.tokenManager.createToken(authentication);
        String resultJson = objectMapper.writeValueAsString(R.ok(token));
        // write header
        response.addHeader(ProjectConfigurationProperties.AUTHORIZATION_HEADER, ProjectConfigurationProperties.TOKEN_PREFIX + token);
        // write body
        R.responseWrite(response, resultJson, HttpServletResponse.SC_OK);
    }

}
